package cn.tedu.system.base.util;

import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
    private static Searcher searcher = null;
    static {
        try {
            InputStream ris = AddressUtils.class.getResourceAsStream("/db/ip2region.xdb");
            byte[] dbBinStr = FileCopyUtils.copyToByteArray(ris);
            searcher = Searcher.newWithBuffer(dbBinStr);
            log.debug("缓存成功！！！！");
        } catch (IOException e) {
            log.error("解析ip地址失败,无法创建搜索器: {}", e);
            throw new RuntimeException(e);
        }
    }

    public static String getCityInfo(String ipAddress) {
        String cityInfo = null;
        try {
            return searcher.search(ipAddress);
        } catch (Exception e) {
            log.error("搜索:{} 失败: {}",ipAddress, e);
        }
        return null;
    }
    /**
     * 根据 IP 地址返回归属地，国内返回但省份，国外返回到国家
     * @param ip IP 地址
     * @return IP 归属地
     */
    public static String getIpRegion(String ip) {
        HashMap<String, String> cityInfo = new HashMap<>();
        String searchIpInfo = getCityInfo(ip);
        if (searchIpInfo == null)return "unknown";
        //-------------------------------------------------------
        //searchIpInfo 的数据格式： 国家|区域|省份|城市|ISP
        //192.168.31.160 0|0|0|内网IP|内网IP
        //47.52.236.180 中国|0|香港|0|阿里云
        //220.248.12.158 中国|0|上海|上海市|联通
        //164.114.53.60 美国|0|华盛顿|0|0
        //-------------------------------------------------------
        String[] splitIpInfo = searchIpInfo.split("\\|");
        cityInfo.put("ip",ip);
        cityInfo.put("searchInfo", searchIpInfo);
        cityInfo.put("country",splitIpInfo[0]);
        cityInfo.put("region",splitIpInfo[1]);
        cityInfo.put("province",splitIpInfo[2]);
        cityInfo.put("city",splitIpInfo[3]);
        cityInfo.put("ISP",splitIpInfo[3]);

        //--------------国内属地返回省份--------------
        if ("中国".equals(cityInfo.get("country"))){
            return cityInfo.get("province");
        }
        //------------------内网 IP----------------
        if ("0".equals(cityInfo.get("country"))){
            if ("内网IP".equals(cityInfo.get("ISP"))){
                return "";
            }
            else return "";
        }
        //--------------国外属地返回国家--------------
        else {
            return cityInfo.get("country");
        }
    }
}
